<template>
  <div class="user-management tech-page">
    <dv-border-box-12 class="tech-header-box">
      <div class="tech-header">
        <h2 class="tech-title">用户管理</h2>
        <div class="tech-stats">
          <div class="stat-item">
            <span class="stat-label">总用户数</span>
            <span class="stat-value">{{ total }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">在线用户</span>
            <span class="stat-value">{{ onlineCount }}</span>
          </div>
        </div>
      </div>
    </dv-border-box-12>

    <dv-border-box-8 class="tech-search-box">
      <div class="tech-search-bar">
        <el-form :inline="true" :model="searchForm" class="tech-search-form">
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
              class="tech-input"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              class="tech-button tech-button--primary"
              @click="handleSearch"
              :loading="loading"
            >
              <el-icon><search /></el-icon>搜索
            </el-button>
            <el-button class="tech-button" @click="resetSearch">
              <el-icon><refresh /></el-icon>重置
            </el-button>
            <el-button
              v-if="currentLoginUser.username === 'admin'"
              type="success"
              class="tech-button tech-button--success"
              @click="handleAddUser"
            >
              <el-icon><plus /></el-icon>新增用户
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </dv-border-box-8>

    <dv-border-box-10 class="tech-table-box">
      <div class="tech-table-container">
        <el-table
          v-loading="loading"
          :data="userList"
          style="width: 100%"
          class="tech-table"
          element-loading-text="数据加载中..."
          element-loading-background="rgba(0, 20, 40, 0.8)"
        >
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          />
          <el-table-column
            prop="username"
            label="用户名"
            min-width="150"
            show-overflow-tooltip
          >
            <template #default="scope">
              <div class="username-cell">
                <el-icon class="user-icon"><user /></el-icon>
                <span class="username-text">{{ scope.row.username }}</span>
                <el-tag
                  v-if="scope.row.username === 'admin'"
                  type="danger"
                  size="small"
                  class="admin-tag"
                >
                  管理员
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            min-width="180"
            sortable
          >
            <template #default="scope">
              <div class="time-cell">
                <el-icon class="time-icon"><clock /></el-icon>
                <span>{{ formatTime(scope.row.createTime) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="Token状态" width="120" align="center">
            <template #default="scope">
              <el-tag
                :type="scope.row.token ? 'success' : 'info'"
                class="tech-tag"
                effect="dark"
              >
                <el-icon><key /></el-icon>
                {{ scope.row.token ? "已授权" : "未授权" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最后活动" min-width="180">
            <template #default="scope">
              <div class="activity-cell">
                <div
                  class="activity-indicator"
                  :class="{ online: isUserOnline(scope.row) }"
                ></div>
                <span>{{ getLastActivity(scope.row) }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="280"
            fixed="right"
            align="center"
          >
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                class="tech-button tech-button--primary"
                @click="handleView(scope.row)"
              >
                <el-icon><view /></el-icon>详情
              </el-button>
              <el-button
                type="success"
                size="small"
                class="tech-button tech-button--success"
                @click="handleEdit(scope.row)"
              >
                <el-icon><edit /></el-icon>编辑
              </el-button>
              <el-button
                v-if="
                  currentLoginUser.username === 'admin' &&
                  scope.row.username !== 'admin'
                "
                type="danger"
                size="small"
                class="tech-button tech-button--danger"
                @click="handleDelete(scope.row)"
              >
                <el-icon><delete /></el-icon>删除
              </el-button>
              <el-button
                v-if="
                  currentLoginUser.username === 'admin' &&
                  scope.row.username !== 'admin'
                "
                type="warning"
                size="small"
                class="tech-button tech-button--warning"
                @click="handleResetToken(scope.row)"
              >
                <el-icon><refresh /></el-icon>重置Token
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="tech-pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="tech-pagination"
          />
        </div>
      </div>
    </dv-border-box-10>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="用户详情"
      width="600px"
      class="tech-dialog"
      :close-on-click-modal="false"
    >
      <div class="user-detail-container">
        <dv-border-box-13 class="detail-box">
          <div class="detail-content">
            <div class="detail-header">
              <div class="user-avatar">
                <el-icon size="40"><user-filled /></el-icon>
              </div>
              <div class="user-basic-info">
                <h3 class="user-name">{{ currentUser.username }}</h3>
                <el-tag
                  v-if="currentUser.username === 'admin'"
                  type="danger"
                  class="admin-badge"
                >
                  系统管理员
                </el-tag>
              </div>
            </div>

            <div class="detail-grid">
              <div class="detail-item">
                <div class="item-label">
                  <el-icon><user /></el-icon>
                  用户名
                </div>
                <div class="item-value">{{ currentUser.username }}</div>
              </div>

              <div class="detail-item">
                <div class="item-label">
                  <el-icon><clock /></el-icon>
                  创建时间
                </div>
                <div class="item-value">
                  {{ formatTime(currentUser.createTime) }}
                </div>
              </div>

              <div class="detail-item">
                <div class="item-label">
                  <el-icon><key /></el-icon>
                  Token状态
                </div>
                <div class="item-value">
                  <el-tag
                    :type="currentUser.token ? 'success' : 'info'"
                    class="tech-tag"
                  >
                    {{ currentUser.token ? "已授权" : "未授权" }}
                  </el-tag>
                </div>
              </div>

              <div class="detail-item full-width">
                <div class="item-label">
                  <el-icon><lock /></el-icon>
                  Token信息
                </div>
                <div class="item-value token-value">
                  <el-input
                    v-model="currentUser.token"
                    type="textarea"
                    :rows="3"
                    readonly
                    class="token-input"
                    placeholder="暂无Token"
                  />
                </div>
              </div>
            </div>
          </div>
        </dv-border-box-13>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button class="tech-button" @click="dialogVisible = false">
            关闭
          </el-button>
          <el-button
            v-if="
              currentLoginUser.username === 'admin' &&
              currentUser.username !== 'admin'
            "
            type="warning"
            class="tech-button tech-button--warning"
            @click="handleResetTokenInDialog"
          >
            <el-icon><refresh /></el-icon>重置Token
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户表单对话框 -->
    <UserFormDialog
      v-model:visible="formDialogVisible"
      :userData="editingUser"
      :isEdit="isEditMode"
      @refresh="fetchUserList"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import cloudbase from "@cloudbase/js-sdk";
import UserFormDialog from "../../components/user/UserFormDialog.vue";

export default {
  name: "UserManagement",
  components: {
    UserFormDialog,
  },
  setup() {
    // 初始化 CloudBase
    const app = cloudbase.init({
      env: "your-env-id",
    });

    // 搜索表单
    const searchForm = reactive({
      username: "",
    });

    // 表格数据
    const loading = ref(false);
    const userList = ref([]);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 对话框相关
    const dialogVisible = ref(false);
    const currentUser = ref({});

    // 用户表单对话框相关
    const formDialogVisible = ref(false);
    const editingUser = ref({});
    const isEditMode = ref(false);

    // 当前登录用户信息
    const currentLoginUser = ref({ username: "admin" }); // 模拟当前登录用户为admin

    // 在线用户数统计
    const onlineCount = computed(() => {
      return userList.value.filter((user) => isUserOnline(user)).length;
    });

    // 初始化数据
    onMounted(async () => {
      // 匿名登录
      try {
        const auth = app.auth();
        const loginState = await auth.getLoginState();

        if (!loginState || !loginState.isLoggedIn) {
          await auth.signInAnonymously();
        }

        fetchUserList();
      } catch (error) {
        console.error("登录失败:", error);
        ElMessage.error("初始化失败，请刷新页面重试");
      }
    });

    // 获取用户列表
    const fetchUserList = async () => {
      loading.value = true;
      try {
        // 确保身份验证
        const auth = app.auth();
        const loginState = await auth.getLoginState();

        if (!loginState || !loginState.isLoggedIn) {
          await auth.signInAnonymously();
          console.log("获取列表前匿名登录成功");
        }

        // 调用云函数获取用户列表
        const result = await app.callFunction({
          name: "admin-user-management",
          data: {
            action: "list",
            data: {
              page: currentPage.value,
              pageSize: pageSize.value,
              username: searchForm.username,
            },
          },
        });

        if (result.result.success) {
          userList.value = result.result.data || [];
          total.value = result.result.total || 0;

          // 如果当前有打开的用户详情对话框，更新其信息
          if (dialogVisible.value && currentUser.value._id) {
            const updatedUser = userList.value.find(
              (u) => u._id === currentUser.value._id
            );
            if (updatedUser) {
              currentUser.value = { ...updatedUser };
            }
          }
        } else {
          ElMessage.error(result.result.message || "获取用户列表失败");
          userList.value = [];
          total.value = 0;
        }
      } catch (error) {
        console.error("获取用户列表失败:", error);
        ElMessage.error("获取用户列表失败: " + (error.message || "网络错误"));
        userList.value = [];
        total.value = 0;
      } finally {
        loading.value = false;
      }
    };

    // 格式化时间
    const formatTime = (time) => {
      if (!time) return "-";
      const date = new Date(time);
      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
      });
    };

    // 判断用户是否在线（简单模拟，实际应该根据token的时效性判断）
    const isUserOnline = (user) => {
      if (!user.token) return false;
      // 简单模拟：有token且创建时间在24小时内认为在线
      const createTime = new Date(user.createTime);
      const now = new Date();
      const diffHours = (now - createTime) / (1000 * 60 * 60);
      return diffHours < 24;
    };

    // 获取最后活动时间
    const getLastActivity = (user) => {
      if (isUserOnline(user)) {
        return "在线";
      }
      return formatTime(user.createTime);
    };

    // 搜索
    const handleSearch = () => {
      currentPage.value = 1;
      fetchUserList();
    };

    // 重置搜索
    const resetSearch = () => {
      searchForm.username = "";
      handleSearch();
    };

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val;
      fetchUserList();
    };

    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchUserList();
    };

    // 查看用户详情
    const handleView = (row) => {
      currentUser.value = { ...row };
      dialogVisible.value = true;
    };

    // 重置用户Token
    const handleResetToken = async (row) => {
      if (currentLoginUser.value.username !== "admin") {
        ElMessage.warning("只有管理员才能重置用户Token");
        return;
      }

      if (row.username === "admin") {
        ElMessage.warning("不能重置管理员用户的Token");
        return;
      }

      try {
        await ElMessageBox.confirm("确认重置该用户的Token吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        loading.value = true;
        // 调用云函数重置token
        const result = await app.callFunction({
          name: "admin-user-management",
          data: {
            action: "update",
            data: {
              _id: row._id,
              // 传空密码，云函数会自动生成新token
              password: "12345678", // 默认重置密码
            },
          },
        });

        if (result.result.success) {
          ElMessage.success("Token重置成功");
          fetchUserList(); // 刷新列表
        } else {
          ElMessage.error(result.result.message || "Token重置失败");
        }
      } catch (error) {
        if (error === "cancel") {
          // 用户取消操作
          return;
        }
        console.error("重置Token失败:", error);
        ElMessage.error("重置Token失败: " + (error.message || "未知错误"));
      } finally {
        loading.value = false;
      }
    };

    // 在对话框中重置Token
    const handleResetTokenInDialog = async () => {
      try {
        await ElMessageBox.confirm("确认重置该用户的Token吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        loading.value = true;
        // 调用云函数重置token
        const result = await app.callFunction({
          name: "admin-user-management",
          data: {
            action: "update",
            data: {
              _id: currentUser.value._id,
              // 传空密码，云函数会自动生成新token
              password: "12345678", // 默认重置密码
            },
          },
        });

        if (result.result.success) {
          ElMessage.success("Token重置成功");
          // 刷新用户列表
          fetchUserList();

          // 刷新当前用户信息
          const updatedUserResult = await app.callFunction({
            name: "admin-user-management",
            data: {
              action: "get",
              data: {
                _id: currentUser.value._id,
              },
            },
          });

          if (updatedUserResult.result.success) {
            currentUser.value = updatedUserResult.result.data;
          }
        } else {
          ElMessage.error(result.result.message || "Token重置失败");
        }
      } catch (error) {
        if (error === "cancel") {
          // 用户取消操作
          return;
        }
        console.error("重置Token失败:", error);
        ElMessage.error("重置Token失败: " + (error.message || "未知错误"));
      } finally {
        loading.value = false;
      }
    };

    // 新增用户
    const handleAddUser = () => {
      if (currentLoginUser.value.username !== "admin") {
        ElMessage.warning("只有管理员才能新增用户");
        return;
      }

      // 重置编辑用户数据
      editingUser.value = {
        username: "",
        password: "",
      };
      isEditMode.value = false;
      formDialogVisible.value = true;
    };

    // 编辑用户
    const handleEdit = (row) => {
      if (
        row.username === "admin" &&
        currentLoginUser.value.username !== "admin"
      ) {
        ElMessage.warning("只有管理员才能编辑管理员账户");
        return;
      }

      // 设置编辑用户数据
      editingUser.value = { ...row };
      // 清空密码字段，避免显示加密后的密码
      editingUser.value.password = "";
      isEditMode.value = true;
      formDialogVisible.value = true;
    };

    // 删除用户
    const handleDelete = async (row) => {
      if (currentLoginUser.value.username !== "admin") {
        ElMessage.warning("只有管理员才能删除用户");
        return;
      }

      if (row.username === "admin") {
        ElMessage.warning("不能删除管理员用户");
        return;
      }

      try {
        await ElMessageBox.confirm(
          `确认删除用户 "${row.username}" 吗？此操作不可恢复！`,
          "删除确认",
          {
            confirmButtonText: "确定删除",
            cancelButtonText: "取消",
            type: "error",
          }
        );

        loading.value = true;
        // 调用云函数删除用户
        const result = await app.callFunction({
          name: "admin-user-management",
          data: {
            action: "delete",
            data: {
              _id: row._id,
            },
          },
        });

        if (result.result.success) {
          ElMessage.success(`用户 ${row.username} 已成功删除`);
          fetchUserList(); // 刷新列表
        } else {
          ElMessage.error(result.result.message || "删除失败");
        }
      } catch (error) {
        if (error === "cancel") {
          // 用户取消操作
          return;
        }
        console.error("删除用户失败:", error);
        ElMessage.error("删除用户失败: " + (error.message || "未知错误"));
      } finally {
        loading.value = false;
      }
    };

    return {
      searchForm,
      loading,
      userList,
      currentPage,
      pageSize,
      total,
      onlineCount,
      dialogVisible,
      currentUser,
      currentLoginUser,
      formatTime,
      isUserOnline,
      getLastActivity,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleView,
      handleResetToken,
      handleResetTokenInDialog,
      handleAddUser,
      handleEdit,
      handleDelete,
      formDialogVisible,
      editingUser,
      isEditMode,
    };
  },
};
</script>

<style scoped>
.user-management {
  padding: 0;
}

.tech-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tech-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.stat-label {
  font-size: 12px;
  color: rgba(0, 192, 255, 0.8);
  text-shadow: 0 0 5px rgba(0, 192, 255, 0.5);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #00c0ff;
  text-shadow: 0 0 10px rgba(0, 192, 255, 0.8);
}

.username-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-icon {
  color: #00c0ff;
}

.username-text {
  flex: 1;
}

.admin-tag {
  background-color: rgba(245, 108, 108, 0.2);
  border: 1px solid #f56c6c;
  color: #f56c6c;
  font-size: 10px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-icon {
  color: rgba(0, 192, 255, 0.6);
}

.activity-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.activity-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #909399;
  box-shadow: 0 0 5px rgba(144, 147, 153, 0.5);
}

.activity-indicator.online {
  background-color: #67c23a;
  box-shadow: 0 0 10px rgba(103, 194, 58, 0.8);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 5px rgba(103, 194, 58, 0.8);
  }
  50% {
    box-shadow: 0 0 15px rgba(103, 194, 58, 1);
  }
  100% {
    box-shadow: 0 0 5px rgba(103, 194, 58, 0.8);
  }
}

.tech-tag {
  background-color: rgba(0, 30, 60, 0.6);
  border: 1px solid rgba(0, 192, 255, 0.5);
  color: #ffffff;
  text-shadow: 0 0 5px rgba(0, 192, 255, 0.5);
}

.tech-dialog :deep(.el-dialog) {
  background-color: rgba(0, 20, 40, 0.95);
  border: 1px solid rgba(0, 192, 255, 0.3);
  box-shadow: 0 0 30px rgba(0, 192, 255, 0.3);
}

.tech-dialog :deep(.el-dialog__header) {
  background-color: rgba(0, 30, 60, 0.8);
  padding: 15px 20px;
  border-bottom: 1px solid rgba(0, 192, 255, 0.5);
}

.tech-dialog :deep(.el-dialog__title) {
  color: #00c0ff;
  font-weight: 600;
  text-shadow: 0 0 10px rgba(0, 192, 255, 0.7);
}

.tech-dialog :deep(.el-dialog__body) {
  background-color: rgba(0, 20, 40, 0.9);
  padding: 20px;
}

.user-detail-container {
  padding: 10px;
}

.detail-box {
  padding: 20px;
}

.detail-content {
  color: #ffffff;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(0, 192, 255, 0.3);
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(
    135deg,
    rgba(0, 192, 255, 0.3),
    rgba(0, 150, 255, 0.3)
  );
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid rgba(0, 192, 255, 0.5);
  box-shadow: 0 0 20px rgba(0, 192, 255, 0.3);
}

.user-avatar .el-icon {
  color: #00c0ff;
}

.user-basic-info {
  flex: 1;
}

.user-name {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #00c0ff;
  text-shadow: 0 0 10px rgba(0, 192, 255, 0.7);
}

.admin-badge {
  background-color: rgba(245, 108, 108, 0.2);
  border: 1px solid #f56c6c;
  color: #f56c6c;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.item-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: rgba(0, 192, 255, 0.8);
  font-weight: 500;
}

.item-label .el-icon {
  color: #00c0ff;
}

.item-value {
  font-size: 16px;
  color: #ffffff;
  padding: 10px;
  background-color: rgba(0, 30, 60, 0.3);
  border: 1px solid rgba(0, 192, 255, 0.2);
  border-radius: 4px;
}

.token-value {
  padding: 0;
  background: none;
  border: none;
}

.token-input :deep(.el-textarea__inner) {
  background-color: rgba(0, 30, 60, 0.5);
  border: 1px solid rgba(0, 192, 255, 0.3);
  color: #ffffff;
  font-family: "Courier New", monospace;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  background-color: rgba(0, 30, 60, 0.8);
  border-top: 1px solid rgba(0, 192, 255, 0.5);
}

.tech-button--warning {
  background-color: rgba(0, 30, 60, 0.6);
  border: 1px solid #e6a23c;
  color: #e6a23c;
  text-shadow: 0 0 5px rgba(230, 162, 60, 0.8);
}

.tech-button--warning:hover {
  background-color: rgba(230, 162, 60, 0.2);
  box-shadow: 0 0 15px rgba(230, 162, 60, 0.7);
}

.tech-button--success {
  background-color: rgba(0, 30, 60, 0.6);
  border: 1px solid #67c23a;
  color: #67c23a;
  text-shadow: 0 0 5px rgba(103, 194, 58, 0.8);
}

.tech-button--success:hover {
  background-color: rgba(103, 194, 58, 0.2);
  box-shadow: 0 0 15px rgba(103, 194, 58, 0.7);
}

.tech-button--danger {
  background-color: rgba(0, 30, 60, 0.6);
  border: 1px solid #f56c6c;
  color: #f56c6c;
  text-shadow: 0 0 5px rgba(245, 108, 108, 0.8);
}

.tech-button--danger:hover {
  background-color: rgba(245, 108, 108, 0.2);
  box-shadow: 0 0 15px rgba(245, 108, 108, 0.7);
}

.tech-input :deep(.el-input__inner) {
  background-color: rgba(0, 30, 60, 0.5);
  border: 1px solid rgba(0, 192, 255, 0.3);
  color: #ffffff;
}

.tech-input :deep(.el-input__inner):focus {
  border-color: #00c0ff;
  box-shadow: 0 0 10px rgba(0, 192, 255, 0.5);
}

.tech-pagination :deep(.el-pagination) {
  color: #ffffff;
}

.tech-pagination :deep(.el-pagination .el-pager li) {
  background-color: rgba(0, 30, 60, 0.6);
  border: 1px solid rgba(0, 192, 255, 0.3);
  color: #ffffff;
}

.tech-pagination :deep(.el-pagination .el-pager li.is-active) {
  background-color: rgba(0, 192, 255, 0.3);
  border-color: #00c0ff;
  color: #00c0ff;
}
</style>
